import { createSlice } from '@reduxjs/toolkit';

const userSlice = createSlice({
  name: 'user',
  initialState: {
    token: localStorage.getItem('token') || null,
    userInfo: null,
    permissions: [],
    roles: [],
  },
  reducers: {
    setUserToken(state, action) {
      state.token = action.payload;
      localStorage.setItem('token', action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    setUserPermissions(state, action) {
      state.permissions = action.payload;
    },
    setUserRoles(state, action) {
      state.roles = action.payload;
    },
    clearUser(state) {
      state.token = null;
      state.userInfo = null;
      state.permissions = [];
      state.roles = [];
      localStorage.removeItem('token');
    },
  },
});

export const { setUserToken, setUserInfo, setUserPermissions, setUserRoles, clearUser } = userSlice.actions;

export const fetchLogin = (values) => async (dispatch) => {
  // 模拟登录请求
  try {
    // 这里应该是一个真实的API调用
    // const response = await api.post('/login', values);
    // 模拟成功响应
    const response = { 
      data: { 
        token: 'fake-token',
        userInfo: {
          id: 1,
          username: 'admin',
          name: '管理员'
        },
        permissions: [
          'user:list', 'user:create', 'user:edit', 'user:delete',
          'role:list', 'role:create', 'role:edit', 'role:delete'
        ],
        roles: ['admin']
      } 
    };

    dispatch(setUserToken(response.data.token));
    dispatch(setUserInfo(response.data.userInfo));
    dispatch(setUserPermissions(response.data.permissions));
    dispatch(setUserRoles(response.data.roles));
    return response.data;
  } catch (error) {
    throw error;
  }
};

export default userSlice.reducer;
